﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataObject.DataAccess;
using DataObject.Database;
using System.Web.Security;

public partial class Pages_Agent_ContractItem : System.Web.UI.Page
{
    #region Properties
    public string ContractId
    {
        get
        {
            if (Request["ContractId"] != null)
                return Request["ContractId"];
            return string.Empty;
        }
    } 
    #endregion
    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadData();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        ContractEntity item = GetContractEntity();
        if (ContractId.Equals(string.Empty))
            ContractDAO.CreateInstant().Add(item);
        else
            ContractDAO.CreateInstant().Update(item);
        Response.Redirect("ContractItem.aspx?ContractId=" + item.ContractID);
    } 
    #endregion
    #region Methods
    protected void LoadData()
    {
        // Load all the guest data
        List<Guest> ls = GuestDAO.CreateInstant().SelectListItem(String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, new HashSet<string>());
        ddlAgent.DataSource = ls;
        ddlAgent.DataTextField = "FullName";
        ddlAgent.DataValueField = "GuestID";
        ddlAgent.DataBind();

        // Get the contract
        ContractEntity item = ContractDAO.CreateInstant().GetContractById(ContractId);
        if (item != null)
        {
            txtContractID.Text = item.ContractID;
            txtExpirationDate.Text = item.ExpirationDate.Value.Date.ToString("dd/MM/yyyy");
            txtStartDate.Text = item.StartDate.Date.ToString("dd/MM/yyyy");
            ddlAgent.SelectedValue = item.AgentID;
            txtPrice.Text = ((int)item.Price).ToString();
            cbActive.Checked = item.Active;
        }
    }

    protected ContractEntity GetContractEntity()
    {
        ContractEntity item = ContractDAO.CreateInstant().GetContractById(ContractId);
        if (item == null)
        {
            item = new ContractEntity();
            item.ContractID = "con/" + DateTime.Now.ToString("ddhhmmss");
            item.CreatedByID = User.Identity.Name;
            item.CreationDate = DateTime.Now;
        }

        item.AgentID = ddlAgent.SelectedValue;
        item.Price = int.Parse(txtPrice.Text);
        item.ModifiedByID = User.Identity.Name;
        item.ModifiedDate = DateTime.Now;
        item.StartDate = Convert.ToDateTime(txtStartDate.Text);
        item.ExpirationDate = Convert.ToDateTime(txtExpirationDate.Text);
        item.Active = cbActive.Checked;
        return item;
    } 
    #endregion
}
